/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.survey.thrift.server;

import static com.vng.zing.survey.data.Base.deserialize;
import com.vng.zing.survey.data.IDSurveyData;
import com.vng.zing.survey.data.IDSurveyHostData;
import com.vng.zing.survey.data.IDSurveyNewData;
import com.vng.zing.survey.data.SurveyData;
import com.vng.zing.survey.data.SurveyStatsData;
import com.vng.zing.survey.data.SurveyStatsPerDayData;
import com.vng.zing.survey.thrift.model.IDSurveyItem;
import com.vng.zing.survey.thrift.model.SurveyItem;
import com.vng.zing.survey.thrift.model.SurveyStatsItem;
import com.vng.zing.survey.thrift.model.SurveyStatsPerDayItem;
import com.vng.zing.survey.utility.TimeDay;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;
import kyotocabinet.Cursor;
import kyotocabinet.DB;
import org.apache.log4j.Logger;

/**
 *
 * @author namhh
 */
public class Statistic extends TimerTask {

    private static int date = 0;
    final Logger logger = Logger.getLogger(Statistic.class);

    public static Date getDate(String date) throws ParseException {
//        String str_Date = String.format("%s:%s:00", hour, minute);
//        String pattern = "dd/MM/yyyy HH:mm:ss";
//        SimpleDateFormat format = new SimpleDateFormat(pattern);

//       String pattern = "dd/MM/yyyy";
//            
//            Date now = new Date();
        //    String strNow = format.format(now);
        String pattern = "dd/MM/yyyy HH:mm:ss";
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        //  strNow = String.format("%s %s:%s:00", strNow,hour,minute);
        return format.parse(date);
    }

    public static String getDate() {

        //SimpleDateFormat ft = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        return "";//ft.format(new Date());
    }

    private int getUniqueDate() {
        try {
            String pattern = "dd/MM/yyyy";
            SimpleDateFormat format = new SimpleDateFormat(pattern);
            Date now = new Date();
            String strNow = format.format(now);
            return (int) (format.parse(strNow).getTime() / 1000);
        } catch (ParseException ex) {
            return -1;
        }
    }

    private int getUniqueDate(String date) {
        try {
            String pattern = "dd/MM/yyyy";
            SimpleDateFormat format = new SimpleDateFormat(pattern);
            return (int) (format.parse(date).getTime() / 1000);
        } catch (ParseException ex) {
            return -1;
        }
    }

    int getUniqueBeforeDate() {
        return getUniqueDate() - 24 * 3600;
    }

    private void UpDateNewSurvey(int idUser, IDSurveyItem iDSurveyItem) {
        try {
            logger.debug(String.format("Call update new survey iduser{%s} id{%s}", idUser, iDSurveyItem.toString()));
            List<Integer> listID = new ArrayList<Integer>();
            listID = iDSurveyItem.getIdSurveys();
            List<Integer> listNew = new ArrayList<Integer>();
            List<Integer> value = new ArrayList<Integer>();
            List<Integer> beginday = new ArrayList<Integer>();
            for (int i = 0; i < listID.size(); i++) {
                int id = listID.get(i);
                SurveyItem surveyItem = SurveyData.getInstance().getSurvey(id);
                if (surveyItem == null) {
                    continue;
                } else {
                    Date today = TimeDay.getDate((int) (new Date().getTime() / 1000));
                    Date begin = TimeDay.getDate(surveyItem.getBeginDay());
                    Date enDate = TimeDay.getDate(surveyItem.getEndDay());
                    if (today.getTime() >= begin.getTime() && today.getTime() <= enDate.getTime()) {
                        SurveyStatsItem statsItem = SurveyStatsData.getInstance().getSurveyStatsItem(id);
                        if (statsItem == null) {
                            statsItem= new SurveyStatsItem(id, 0, 0, null);
                            value.add(0);
                        } else {
                            value.add(statsItem.getView() + statsItem.getResponse() * 2);
                        }
                        UpdateStatistic(id, statsItem);
                        listNew.add(id);
                        beginday.add(surveyItem.getBeginDay());
                    }
                }

            }
            listNew = sort(listNew, beginday);
            IDSurveyItem newiDSurveyItem = new IDSurveyItem(listNew, listNew.size());
            IDSurveyNewData.getInstance().setIDSurveyItem(idUser, newiDSurveyItem);
            List<Integer> result = sort(listNew, value);
            IDSurveyItem iDSurveyItemResult = new IDSurveyItem(result, result.size());
            IDSurveyHostData.getInstance().setIDSurveyItem(idUser, iDSurveyItemResult);

        } catch (Exception ex) {
            logger.error(ex.toString());
        }
    }

    List<Integer> UpDateHotSurvey(int idUser, IDSurveyItem iDSurveyItem) {
        try {
            logger.debug(String.format("Call update HOT survey iduser{%s} id{%s}", idUser, iDSurveyItem.toString()));
            List<Integer> listID = new ArrayList<Integer>();
            listID = iDSurveyItem.getIdSurveys();
            List<Integer> value = new ArrayList<Integer>(listID.size());

            for (int i = 0; i < listID.size(); i++) {
                int id = listID.get(i);
                SurveyStatsItem statsItem = SurveyStatsData.getInstance().getSurveyStatsItem(id);
                if (statsItem == null) {
                    continue;
                } else {
                    value.add(i, statsItem.getView() + statsItem.getResponse() * 2);

                }
            }
            List<Integer> result = sort(listID, value);
            IDSurveyItem iDSurveyItemResult = new IDSurveyItem(result, result.size());
            IDSurveyHostData.getInstance().setIDSurveyItem(idUser, iDSurveyItemResult);
            return listID;
        } catch (Exception ex) {
            logger.error(ex.toString());
        }
        return null;
    }

    private void UpdateStatistic(int id, SurveyStatsItem statsItem) {
    logger.debug(String.format("Call update statistic idsurvey{%s} statsItem{%s}", id, statsItem));
        Date today = TimeDay.getDate((int) (new Date().getTime() / 1000));
        Date beforDay = TimeDay.beforDay(today);
        Date beforTwoDay = TimeDay.beforDay(beforDay);
        int viewPerDay;
        int responsePerDay;
        int totalView;
        int totalResponse;
        SurveyStatsPerDayItem oldSurveyStatsPerDayItem = SurveyStatsPerDayData.getInstance().getSurveyStatsPerDayItem(id, (int) (beforTwoDay.getTime() / 1000));

        if (oldSurveyStatsPerDayItem == null) {
            totalView = statsItem.getView();
            totalResponse = statsItem.getResponse();
            viewPerDay = totalView;
            responsePerDay = totalResponse;
        } else {
            totalView = statsItem.getView();
            totalResponse = statsItem.getResponse();
            viewPerDay = statsItem.getView() - oldSurveyStatsPerDayItem.getView();
            responsePerDay = statsItem.getResponse() - oldSurveyStatsPerDayItem.getResponse();
        }
        SurveyStatsPerDayItem surveyStatsPerDayItem = new SurveyStatsPerDayItem(totalView, totalResponse, viewPerDay, responsePerDay, (int) (beforDay.getTime() / 1000));
        SurveyStatsPerDayData.getInstance().setSurveyStatsPerDayItem(id, (int) (beforDay.getTime() / 1000), surveyStatsPerDayItem);
    }

    private List<Integer> sort(List<Integer> id, List<Integer> value) {
        List<Integer> result = new ArrayList<Integer>(id.size());
        result = id;
        for (int i = 0; i < id.size() - 1; i++) {
            for (int j = i + 1; j < id.size(); j++) {
                if (value.get(i) < value.get(j)) {
                    int temp = result.get(i);
                    result.set(i, result.get(j));
                    result.set(j, temp);

                    temp = value.get(i);
                    value.set(i, value.get(j));
                    value.set(j, temp);
                }
            }
        }
        return result;
    }

    private void excute() throws IOException, ClassNotFoundException {
        try {
////////////////// for testing///////////////////
            date++;
            ///////////////////////////////
            DB db = IDSurveyData.getInstance().get();

            // traverse records
            Cursor cur = db.cursor();

            cur.jump();
            byte[][] rec;
            while ((rec = cur.get(true)) != null) {

                Integer idUser = (Integer) deserialize(rec[0]);
                IDSurveyItem iDSurveyItem = (IDSurveyItem) deserialize(rec[1]);
                UpDateNewSurvey(idUser, iDSurveyItem);
            }
            cur.disable();

        } catch (Exception ex) {
            logger.error(ex.toString());
        }

    }

    @Override
    public void run() {
        try {

            logger.debug("Running statistic ");
            excute();
            logger.debug("Statistic finished! ");
        } catch (Exception ex) {
            logger.debug(ex.toString());
        }
    }
}
